<template>
	<view>
		<u-toast ref="uToast"></u-toast>
		<scroll-view scroll-y class="content">
			<u-list  v-if="list.length > 0">
				<u-list-item v-for="item in list" :key="item.id">
					<view class="address-item">
						<view class="info titleInfo u-flex u-row-between" @click="openProject(item.id)">
							<text class="title">{{ item.project.name }} （{{getProjectType(item.service_type)}}）</text>
							<u-icon name="arrow-right" color="#999" size="14"></u-icon>
							<text class="tag">{{ getStatusText(item.status) }}</text>
						</view>
						<!-- 内容区域 -->
						<view class="content-wrapper u-flex" @click="openOrder(item.id)">
							<view class="project-l">
								<image mode="aspectFill" :src="item.project.cover_img" lazy-load />
							</view>
							<view class="project-r">
								<view v-if="item.service_type=='day'" class="address">预约：{{ formatTimeRange(item.service_start) }}</view>
								<view v-else class="address">预约：{{ formatTimeRange(item.service_start) }} 至 {{ formatTimeRange(item.service_end) }}</view>
								<view class="address">地址：{{ item.city }}{{ item.district }}{{ item.address }}</view>
								<view class="address">备注：{{ item.remarks }}</view>
								<view class="address">下单：{{ item.create_datetime }}</view>
							</view>
						</view>
						<view v-if="userPermissions" class="actions u-flex u-row-between">
							<view style="display: flex;">
								<text class="totalText">{{userPermissions && userPermissions[0].role_key == "user"?"实付:":"金额:"}}</text>
								<view class="totalAmount">{{ userPermissions && userPermissions[0].role_key == "user"? item.total_amount / 100 : item.total_amount / 100 * Number(item.project.serviceman_price*0.01)  }} 元</view>
							</view>
							<view style="align-items: center;">
								<!-- 将 v-for 和 :key 移到真实元素 u-button 上 -->
								<button
									v-for="btn in getActionButtons(item)"
									plain="true"
									:key="item.id"
									:type="btn.type"
									:open-type="btn.actionType=='contact'?'contact':''"
									size="mini"
									@click="handleAction(btn.actionType, item)"
									class="action-btn"
								>
									{{ btn.text }}
								</button>
							</view>
						</view>
						<!-- 						<view class="actions">
							<u-button type="warning" size="mini" @click="editAddress(item.id)">编辑</u-button>
							<u-button type="error" size="mini" @click="deleteAddress(item.id)">删除</u-button>
						</view> -->
					</view>
				</u-list-item>
			</u-list>
			<!-- 无数据时显示图片 -->
			<view v-else class="no-data">
				<image src="/static/mescroll-empty.png" mode="aspectFit" class="no-data-img"></image>
				<text class="no-data-text">暂无数据</text>
			</view>
		</scroll-view>
	</view>
</template>

<script>
import { mapState } from 'vuex';
import store from '@/store';
import { putOrder,payRefund  } from '@/apis/order_callback.js';


export default {
	props: {
		list: {
			type: Array,
			default: []
		}
	},
	data() {
		return {
			// 按钮配置表
			buttonConfig: {
				user: {
					pending: [{ text: '取消', type: 'warn', actionType: 'cancel' }],
					assigned: [{ text: '取消', type: 'warn', actionType: 'cancel' }],
					inProgress: [{ text: '客服', type: 'primary', actionType: 'contact' },{ text: '查看', type: 'default', actionType: 'view' }],
					confirm: [{ text: '验收', type: 'primary', actionType: 'complete' }],
					completed: [{ text: '查看', type: 'default', actionType: 'view' }],
					refund: [{ text: '查看', type: 'default', actionType: 'view' }],
					refundFail: [{ text: '查看', type: 'default', actionType: 'view' }],
					cancelled: [{ text: '查看', type: 'default', actionType: 'view' }]
				},
				work: {
					pending: [{ text: '接单', type: 'primary', actionType: 'accept' }],
					assigned: [
						{ text: '开始', type: 'primary', actionType: 'start' },
						{ text: '取消', type: 'warn', actionType: 'cancel' }
					],
					inProgress: [{ text: '完成', type: 'primary', actionType: 'finish' }],
					confirm: [{ text: '查看', type: 'default', actionType: 'view' }],
					completed: [{ text: '查看', type: 'default', actionType: 'view' }],
					cancelled: [{ text: '查看', type: 'default', actionType: 'view' }]
				}
			}
		};
	},
	computed: {
		...mapState(['userInfo']),

		// 这里可以根据 Vuex 或其他状态管理获取用户权限
		userPermissions() {
			// 假设从 Vuex 获取用户权限
			return this.userInfo.roles || [];
		},
		// isLoggedIn() {
		// 	// 假设从 Vuex 获取登录状态
		// 	return this.userInfo.token;
		// },
		isUserId() {
			// 假设从 Vuex 获取登录状态
			return this.userInfo.id;
		}
	},
	//第一次加载
	created(e) {},
	methods: {
		onJump(url) {
			uni.navigateTo({
				url: url
			});
		},
		// 状态文本映射
		getStatusText(status) {
			const statusMap = {
				pending: '待服务',
				assigned: '待服务',
				inProgress: '进行中',
				confirm: '待验收',
				completed: '已完成',
				refund: '退款中',
				refundFail: '退款失败',
				cancelled: '已取消'
			};
			return statusMap[status] || status;
		},
		// 项目类型文本映射
		getProjectType(type) {
			const typeMap = {
				day: '天',
				month: '月',
				quarter: '季',
				year: '年'
			};
			return typeMap[type] || type;
		},
		formatTimeRange(timeRange) {
			if (!timeRange || typeof timeRange !== 'string') return '';

			// 按波浪号分割成开始时间和结束时间
			const times = timeRange.split('~');
			if (times.length !== 2) return timeRange; // 格式不正确就返回原值

			const start = times[0].trim(); // "2025-05-13 10:00:00"
			const end = times[1].trim(); // "2025-05-13 11:00:00"

			// 提取日期部分（前10位）和时间部分（后8位）
			const startDate = start.substring(0, 10); // "2025-05-13"
			const startTime = start.substring(11, 16); // "10:00"
			const endTime = end.substring(11, 16); // "11:00"

			// 组合输出格式
			return `${startDate} ${startTime}-${endTime}`;
		},
		/**
		 * 根据角色和状态获取对应的操作按钮
		 * @param {Object} item 订单对象
		 * @returns {Array} 按钮配置数组
		 */
		getActionButtons(item) {
			const role = this.userPermissions[0].role_key;
			const status = item.status;

			// 返回对应的按钮配置，如果没有匹配项返回空数组
			return this.buttonConfig[role]?.[status] || [];
		},

		/**
		 * 统一处理所有按钮点击事件
		 * @param {string} actionType 操作类型
		 * @param {Object} item 订单对象
		 */
		handleAction(actionType, item) {
			switch (actionType) {
				case 'cancel':
					this.handleCancel(item.id);
					break;
				case 'accept':
					this.handleAccept(item.id);
					break;
				case 'start':
					this.handleStart(item.id);
					break;
				case 'finish':
					this.handleFinish(item.id);
					break;
				case 'complete':
					this.handleComplete(item.id);
					break;
				case 'view':
					this.handleView(item.id);
					break;
				case 'contact':
					break;
				default:
					console.warn('未知操作类型:', actionType);
			}
		},

		openOrder(id) {
			uni.navigateTo({
				url: '/pages2/order/detail?id=' + id
			});
		},
		openProject(id) {
			uni.navigateTo({
				url: '/pages2/order/detail?id=' + id
			});
		},
		// 具体操作处理函数
		handleCancel(id) {
			if (this.userPermissions[0].role_key == 'work') {
				this.putOrderData({ status: 'pending',worker_id:null,  }, id, '你确认取消此订单吗？');
			}else{
				this.refundOrder({ pay_type: 'mpwxpay',orderId:id,  }, '你确认取消此订单吗？');
			}
			// 处理取消逻辑
		},
		handleAccept(id) {
			if (this.userPermissions[0].role_key == 'work') {
				this.putOrderData({ status: 'assigned',worker_id:this.isUserId }, id, '你确认接此订单吗？');
			}
			// 处理接单逻辑
		},
		handleStart(id) {
			if (this.userPermissions[0].role_key == 'work') {
				this.putOrderData({ status: 'inProgress'}, id, '你确认开始订单吗？');
			}
			// 处理开始逻辑
		},
		handleFinish(id) {
			if (this.userPermissions[0].role_key == 'work') {
				this.putOrderData({ status: 'confirm'}, id, '和客户确认过完成吗？');
			}
			// 处理完成逻辑
		},
		handleComplete(id) {
			if (this.userPermissions[0].role_key == 'user') {
				this.putOrderData({ status: 'completed'}, id, '确认已经完成了吗？');
			}
			// 处理验收完成逻辑
		},
		handleView(id) {
			this.openOrder(id);
			// 处理查看逻辑
		},
		putOrderData(status, id, mes) {
			uni.showModal({
				title: '温馨提示',
				content: mes,
				success: async (res) => {
					if (res.confirm) {
						store.commit('setLoadingShow', true);
						putOrder(
							status,
							id,
							() => {
								this.$refs.uToast.show({
									type: 'success',
									position: 'top',
									title: '提示',
									message: '成功'
								});
								this.$emit('down');
								store.commit('setLoadingShow', false);
							},
							(err) => {
								this.$refs.uToast.show({
									type: 'error',
									position: 'top',
									title: '错误',
									message: '失败'
								});
								store.commit('setLoadingShow', false);
							}
						);
					}
				}
			});
		},
		
		refundOrder(param, mes) {
			uni.showModal({
				title: '温馨提示',
				content: mes,
				success: async (res) => {
					if (res.confirm) {
						store.commit('setLoadingShow', true);
						payRefund(
							param,
							(res) => {
								if(res.code == 200){
									this.$refs.uToast.show({
										type: 'success',
										position: 'top',
										title: '提示',
										message: '申请退款成功,请刷新！'
									});
									this.$emit('down');
								}else{
									this.$refs.uToast.show({
										type: 'error',
										position: 'top',
										title: '提示',
										message: res.result
									});
								}
								store.commit('setLoadingShow', false);
							},
							(err) => {
								this.$refs.uToast.show({
									type: 'error',
									position: 'top',
									title: '错误',
									message: '申请退款失败'
								});
								store.commit('setLoadingShow', false);
							}
						);
					}
				}
			});
		}
	}
};
</script>
<style lang="scss" scoped>
@import '@/common/variables.scss'; // ✅ 必须引入

/* 新增无数据样式 */
.no-data {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	height: 70vh; /* 占据70%的视口高度 */
	padding: 40rpx;
	
	.no-data-img {
		width: 300rpx;
		height: 300rpx;
		opacity: 0.6;
	}
	
	.no-data-text {
		font-size: 28rpx;
		color: #999;
		margin-top: 30rpx;
	}
}

.content-wrapper {
	display: flex;
	margin-top: 20rpx;
}
/* 优化后的样式 */
.container {
	background: #f5f5f5;
	min-height: 100vh;
}

.content {
	padding: 24rpx; /* 增加容器内边距 */
	padding-bottom: 0px;
	box-sizing: border-box;
}

.address-item {
	background: #fff;
	border-radius: 16rpx;
	margin-bottom: 24rpx;
	padding: 32rpx;
	position: relative;

	/* 双重边框效果 */
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.04),
		// 外层浅阴影
		0 0 0 1rpx rgba(0, 0, 0, 0.06); // 内层边框阴影
}
.titleInfo {
	color: #666;
	line-height: 1.6;
	padding-bottom: 16rpx;
	border-bottom: 1rpx solid #eee;
}

.project-r {
	width: calc(100% - 90px);
	padding-left: 10rpx;
}

.info {
	display: flex;
	align-items: center;
	margin-bottom: 16rpx;

	.name {
		font-size: $font-size-base;
		font-weight: 500;
		color: #333;
		margin-right: 24rpx;
	}

	.title {
		font-size: $font-size-base;
		font-weight: 600;
		// color: #333;
		margin-right: 24rpx;
	}

	.phone {
		font-size: $font-size-base;
		color: #666;
	}

	.tag {
		margin-left: auto;
		padding: 4rpx 16rpx;
		font-size: $font-size-base;
	}
}

// .project-l {
// 	width: 80px;
// 	height: 80px;
// 	align-items: center;
// }

// .project-l image {
// 	width: 80px;
// 	height: 80px;
// 	object-fit: cover;
// }

.project-l {
	width: 150rpx;
	height: 150rpx;
	border-radius: 12rpx;
	overflow: hidden;
	margin-right: 20rpx;

	image {
		width: 100%;
		height: 100%;
	}
}

.address {
	text-overflow: ellipsis;
	overflow: hidden;
	display: -webkit-box;
	-webkit-box-orient: vertical;
	-webkit-line-clamp: 1; /* 控制显示几行 */
	font-size: $font-size-sm;
	color: #666;
	line-height: 1.4;
	// line-height: 1.6;
	margin-bottom: 10rpx;
	// border-bottom: 1rpx solid #eee;
}

.actions {
	justify-content: space-between;
	align-items: center;
	margin-top: 16rpx;
	padding-top: 16rpx;
	display: flex;
	gap: 20rpx;
	border-top: 1rpx solid #eee;
}
.totalAmount {
	font-weight: 600;
	font-size: $font-size-base;
	color: #ff6600;
	justify-content: flex-start;
	padding-left: 20rpx;
}

.totalText {
	font-size: $font-size-base;
	color: #666;
	justify-content: flex-start;
}

.action-btn {
	font-size: $font-size-sm;
	margin-left: auto;
	margin-left: 30rpx;
	width: 120rpx;
	height: 60rpx;
}
</style>
